package com.fairylove.rpc.transport.socket.client;

import com.fairylove.rpc.api.HelloObject;
import com.fairylove.rpc.api.HelloService;
import com.fairylove.rpc.entity.RpcRequest;
import com.fairylove.rpc.entity.RpcResponse;
import com.fairylove.rpc.serializer.CommonSerializer;
import com.fairylove.rpc.serializer.SerializeException;
import com.fairylove.rpc.transport.socket.RpcClient;
import com.fairylove.rpc.transport.socket.RpcClientProxy;
import com.fairylove.rpc.transport.utils.ObjectReader;
import com.fairylove.rpc.transport.utils.ObjectWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.Socket;

import static com.fairylove.rpc.serializer.CommonSerializer.DEFAULT_SERIALIZER;

public class SocketClient implements RpcClient {
    private static final Logger logger = LoggerFactory.getLogger(SocketClient.class);

    private CommonSerializer serializer;
    private String host;
    private Integer port;
    //选择序列化方式 默认是kryo
    public SocketClient(){
        this(DEFAULT_SERIALIZER);
    }

    public SocketClient(Integer serializer){
        this.serializer = CommonSerializer.getByCode(serializer);
    }
    public SocketClient(String host,int port,Integer serializer){
        this.serializer = CommonSerializer.getByCode(serializer);
        this.host = host;
        this.port = port;
    }

    public Object sendRequest(RpcRequest rpcRequest){
        if(serializer == null){
            logger.info("序列化方式未设置");
            throw new SerializeException("序列化方式未设置");
        }
        System.out.println(host + port);
        try(Socket socket = new Socket(host,port)) {
            OutputStream outputStream = socket.getOutputStream();
//            objectOutputStream.writeObject(message);//序列化
            ObjectWriter.writeObject(outputStream, rpcRequest, serializer);
            InputStream inputStream = socket.getInputStream();
//            Object obj = objectInputStream.readObject(); //反序列化
            final RpcResponse rpcResponse = (RpcResponse)ObjectReader.readObject(inputStream);
            if (rpcResponse == null){
               logger.error("服务调用失败 service:{}",rpcRequest.getInterfaceName());
            }
            return  rpcResponse;
        }  catch (IOException  e) {
            logger.info("occur execption"+ e);
        }
        return  null;
    }


}
